package com.wjs.gulimall.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.to.es.SkuEsModel;
import com.wjs.gulimall.config.GulimallElstaicSerchConfig;
import com.wjs.gulimall.constant.EsConstant;
import com.wjs.gulimall.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ProductSaveServiceImp implements ProductSaveService {

    @Autowired
    private RestHighLevelClient esRestClient;
    @Override
    public Boolean SaveProduct(List<SkuEsModel> skuEsModels) throws IOException {
        // 建立索引

        // 往索引里面添加数据
        BulkRequest request=new BulkRequest();
        for (SkuEsModel esModel : skuEsModels) {
            //指定索引
            IndexRequest indexRequest=new IndexRequest(EsConstant.Es_index);
            indexRequest.id(esModel.getSkuId().toString());
            String jsonString = JSON.toJSONString(esModel);
            indexRequest.source(jsonString, XContentType.JSON);
            request.add(indexRequest);
        }
        BulkResponse bulk = esRestClient.bulk(request, GulimallElstaicSerchConfig.COMMON_OPTIONS);
        boolean b = bulk.hasFailures();
        List<String> collect = Arrays.stream(bulk.getItems()).map((item) -> {
            return item.getId();
        }).collect(Collectors.toList());
        log.error("商品上架错误,{}",collect);
        return b;
    }
}
